package com.sunyard.base.base

import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.annotation.DrawableRes
import androidx.lifecycle.Observer
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper
import com.blankj.utilcode.util.LogUtils
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.sunyard.base.base.hjq.BaseActivity
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.sunyard.base.R
import com.sunyard.base.ktExt.getViewModel
import com.sunyard.base.ktExt.toast
import com.sunyard.base.viewModel.BaseViewModel
import com.sunyard.base.widget.StatusManager


abstract class BaseActivity<T : BaseViewModel> : BaseActivity(), BGASwipeBackHelper.Delegate,
    OnTitleBarListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        initSwipeBackFinish();
        super.onCreate(savedInstanceState)
    }

    override fun getLayoutId(): Int {
        return if (initLayout() == null) {
            0
        } else {
            initLayout()!!
        }
    }

    override fun getTitleId() = 0
    var titleBar: TitleBar? = null
    override fun onLeftClick(v: View?) {
        onBackPressed()
    }

    override fun onRightClick(v: View?) {

    }

    override fun onTitleClick(v: View?) {

    }

    override fun initViewInterFace() {
        LogUtils.d("初始化 Activity")

        viewModel = getViewModel(initViewModel())
        initTitleBar()
        if (needShowMsg()) {
            initMsgLiveData()
            initCodeLiveData()
        }
        initLiveData()
        initView()
    }


    open fun needShowMsg() = true
    private fun initMsgLiveData() {
        viewModel?.msg?.observe(this, Observer {
            if (!viewModel?.showMsgOK?.value!!) {
                toast(it)
                viewModel?.showMsgOK?.value = true
            }
            showComplete()
            stopLoadMoreRefresh()
        })
    }

    private fun initCodeLiveData() {
        viewModel?.code?.observe(this, Observer {
            if (!viewModel?.showCodeOK?.value!!) {
                showError()
                viewModel?.showCodeOK?.value = true
            }
        })
    }


    override fun initData() {

    }


    var viewModel: T? = null


    /**
     * 如果由需要，重写此方法 初始化layoutView,最后一步
     * */
    private fun initLayoutView(): View? {
        return null
    }

    /**
     * 返回layout布局
     * */
    abstract fun initLayout(): Int?

    /**
     * 初始化viewModel
     * */
    abstract fun initViewModel(): Class<T>

    /**
     * 初始化对liveData的监听处理
     * */
    abstract fun initLiveData()

    /**
     * 初始化组件响应事件
     * */
    abstract fun initView()

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_DOWN) {
            hideSoftKeyboard()
        }
        return super.onTouchEvent(event)
    }

    /**
     * 隐藏软键盘
     */
    private fun hideSoftKeyboard() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        val view = currentFocus
        if (view != null) {
            val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
            view.post {
                manager?.hideSoftInputFromWindow(view.windowToken, 0)
            }
        }
    }


    fun <K> startActivity(cls: Class<K>, data: String) {
        val intent = Intent()
        intent.setClass(this, cls)
        intent.putExtra("data", data)
        startActivity(intent)
    }

    fun <K> startActivityNewTask(cls: Class<K>) {
        val intent = Intent()
        intent.setClass(this, cls)
        intent.flags = FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }


    private val mStatusManager = StatusManager()
    /**
     * 显示加载中
     */
    fun showLoading() {
        mStatusManager.showLoading(this)
    }

    /**
     * 显示加载完成
     */
    fun showComplete() {
        mStatusManager.showComplete()
    }

    /**
     * 显示空提示
     */
    fun showEmpty() {
        mStatusManager.showEmpty(contentView)
    }

    /**
     * 显示错误提示
     */
    fun showError() {
        mStatusManager.showError(contentView)
    }

    /**
     * 显示自定义提示
     */
    fun showLayout(@DrawableRes iconId: Int, textStr: String) {
        mStatusManager.showLayout(contentView, iconId, textStr)
    }

    fun showLayout(drawable: Drawable, hint: CharSequence) {
        mStatusManager.showLayout(contentView, drawable, hint)
    }


    // 加载布局
    private var mSmartRefreshLayout: SmartRefreshLayout? = null

    fun initSwipeRefresh(listener: OnRefreshLoadMoreListener) {
        showComplete()
        val view: View = contentView
        if (mSmartRefreshLayout == null) {

            if (view is SmartRefreshLayout) {
                mSmartRefreshLayout = view
            } else if (view is ViewGroup) {
                mSmartRefreshLayout = findSmartRefreshLayout(view)
            }
//            LogUtils.e("You didn't add this SmartRefreshLayout to your Activity layout")
//            checkNotNull(mSmartRefreshLayout) { "You didn't add this SmartRefreshLayout to your Activity layout" }
        }

        mSmartRefreshLayout?.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                listener.onLoadMore(refreshLayout)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                listener.onRefresh(refreshLayout)
            }
        })
    }

    fun stopLoadMoreRefresh() {
        mSmartRefreshLayout?.finishLoadMore()
        mSmartRefreshLayout?.finishRefresh()
    }

    /**
     * 智能获取布局中的 SwipeRefreshLayout 对象
     */
    private fun findSmartRefreshLayout(group: ViewGroup): SmartRefreshLayout? {
        for (i in 0 until group.childCount) {
            val view = group.getChildAt(i)
            if (view is SmartRefreshLayout) {
                return view
            } else if (view is ViewGroup) {
                val layout = findSmartRefreshLayout(view)
                if (layout != null) return layout
            }
        }
        return null
    }


    fun initTitleBar() {
        val view: View = contentView
        if (titleBar == null) {

            if (view is TitleBar) {
                titleBar = view
            } else if (view is ViewGroup) {
                titleBar = findTitleBar(view)
            }

//            check(titleBar) { "You didn't add this titleBar to your Activity layout" }
        }
        titleBar?.setOnTitleBarListener(this)
    }


    /**
     * 智能获取布局中的 SwipeRefreshLayout 对象
     */
    private fun findTitleBar(group: ViewGroup): TitleBar? {
        for (i in 0 until group.childCount) {
            val view = group.getChildAt(i)
            if (view is TitleBar) {
                return view
            } else if (view is ViewGroup) {
                val titleBar = findTitleBar(view)
                if (titleBar != null) return titleBar
            }
        }
        return null
    }

    /**************************侧滑返回*********************************/
    var mSwipeBackHelper: BGASwipeBackHelper? = null

    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    fun initSwipeBackFinish() {
        mSwipeBackHelper = BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。
        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper?.setSwipeBackEnable(true)
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper?.setIsOnlyTrackingLeftEdge(true)
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper?.setIsWeChatStyle(true)
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper?.setShadowResId(R.drawable.bga_sbl_shadow)
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper?.setIsNeedShowShadow(true)
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper?.setIsShadowAlphaGradient(true)
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper?.setSwipeBackThreshold(0.3f)
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper?.setIsNavigationBarOverlap(false)
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    override fun isSupportSwipeBack(): Boolean {
        return true
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */

    override fun onSwipeBackLayoutSlide(slideOffset: Float) {}

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    override fun onSwipeBackLayoutCancel() {}

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    override fun onSwipeBackLayoutExecuted() {
        mSwipeBackHelper?.swipeBackward();
    }

    override fun onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件
//        showComplete()
        if (mSwipeBackHelper != null) {
            if (mSwipeBackHelper!!.isSliding) {
                return
            }
            mSwipeBackHelper!!.backward()
        } else {

            super.onBackPressed()
        }
    }

    override fun onStart() {
        super.onStart()

    }

    override fun onStop() {
        super.onStop()

    }
}
